'use client'

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function AdminHome() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  useEffect(() => {
    const checkLoginStatus = async () => {
      try {
        const token = document.cookie
          .split('; ')
          .find(row => row.startsWith('admin_session='))?
          .split('=')[1];

        if (!token) {
          setLoading(false);
          return;
        }

        const response = await fetch('/api/admin/auth', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });

        const data = await response.json();
        if (data.success && data.isLoggedIn) {
          setIsLoggedIn(true);
        }
      } catch (error) {
        console.error('检查登录状态失败:', error);
      } finally {
        setLoading(false);
      }
    };

    checkLoginStatus();
  }, [router]);

  const handleLogout = async () => {
    try {
      await fetch('/api/admin/auth', {
        method: 'DELETE',
      });
      setIsLoggedIn(false);
      router.refresh();
    } catch (error) {
      console.error('登出失败:', error);
    }
  };

  if (loading) {
    return <div className="container mx-auto py-8 px-4 flex justify-center items-center h-screen">加载中...</div>;
  }

  if (!isLoggedIn) {
    router.push('/admin/login');
    return null;
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="max-w-md mx-auto">
        <Card>
          <CardHeader>
            <CardTitle>管理后台</CardTitle>
            <CardDescription>软件著作权申请管理系统</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="text-center">
                <h2 className="text-lg font-semibold mb-2">欢迎使用管理后台</h2>
                <p className="text-sm text-muted-foreground">
                  这里可以查看和管理所有的软件著作权申请记录
                </p>
              </div>
              
              <div className="space-y-2">
                <Button asChild className="w-full">
                  <Link href="/admin/dashboard">
                    进入管理面板
                  </Link>
                </Button>
                
                <Button asChild variant="outline" className="w-full">
                  <Link href="/admin/change-password">
                    更改管理员密码
                  </Link>
                </Button>
                
                <Button asChild variant="outline" className="w-full">
                  <Link href="/generator">
                    返回生成器
                  </Link>
                </Button>
                
                <Button variant="destructive" className="w-full" onClick={handleLogout}>
                  登出
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}